package com.health.config;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class FilterConfig implements Filter {
    @Override
    public void init(jakarta.servlet.FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 将 ServletRequest 和 ServletResponse 转换为 HttpServletRequest 和 HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        boolean isDebug = true;

        if(isDebug == true) {
            filterChain.doFilter(request, response);
            return;
        }


        // 检查请求的 URI 是否是 /user/login
        if (request.getRequestURI().equals("/Health/user/login") || request.getRequestURI().equals("/Health/user/logOff")
            || request.getRequestURI().equals("/Health/user/register")
            || request.getRequestURI().equals("/Health/user/registerDoctor") || request.getRequestURI().equals("/Health/user/registerPatient")) {
            // 放行登录请求
            filterChain.doFilter(request, response);
            return;
        }

         // 检查请求的 URI 是否是 /user/login
        if (request.getRequestURI().equals("/Health/user/logOff")) {
            // 放行登录请求
            filterChain.doFilter(request, response);
            return;
        }


        // 从请求头中获取 Authorization 字段
        String authorizationHeader = request.getHeader("Authorization");

        // 检查 Authorization 字段是否存在且以 "Bearer " 开头
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                // 提取 Token 值（去除 "Bearer " 前）缀
                String token = authorizationHeader.substring(7);

                // 使用 JwtUtil 解析 Token
                Claims claims = JwtUtil.parseToken(token);

                // 如果 Token 有效，继续处理请求链
                if (claims != null) {
                    filterChain.doFilter(request, response);
                } else {
                    // 如果 Token 无效，返回 401 未授权状态码和错误信息
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
                }
            } catch (Exception e) {
                // 捕获解析 Token 时的异常，返回 401 未授权状态码和错误信息
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token");
            }
        } else {
            // 如果没有提供 Token 或格式不正确，返回 401 未授权状态码和错误信息
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token is missing or invalid");
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
